﻿using Furion;
using Furion.DependencyInjection;
using Furion.EventBus;
using Furion.FriendlyException;
using FurionApi.Demo.Core.Const;
using FurionApi.Demo.Core.EventSubscriber.Dto;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace FurionApi.Demo.Web.Core.Filter
{
    public class LogExceptionHandler : IGlobalExceptionHandler, ISingleton
    {
        private readonly ILogger<LogExceptionHandler> logger;
        private readonly IEventPublisher eventPublisher;

        public LogExceptionHandler(ILogger<LogExceptionHandler> logger, IEventPublisher eventPublisher) {
            this.logger = logger;
            this.eventPublisher = eventPublisher;
        }


        public async Task OnExceptionAsync(ExceptionContext context)
        {
            if (context.Exception?.GetType() == typeof(AppFriendlyException)) 
                return;
            var userContext = App.User;
            await eventPublisher.PublishAsync(new ChannelEventSource("Create:ExLog", new SysLogEx
            {
                Account = userContext?.FindFirstValue(ClaimConst.CLAINM_ACCOUNT),
                Name = userContext?.FindFirstValue(ClaimConst.CLAINM_NAME),
                ClassName = context.Exception.TargetSite.DeclaringType?.FullName,
                MethodName = context.Exception.TargetSite.Name,
                ExceptionName = context.Exception.Message,
                ExceptionMsg = context.Exception.Message,
                ExceptionSource = context.Exception.Source,
                StackTrace = context.Exception.StackTrace,
                ParamsObj = context.Exception.TargetSite.GetParameters().ToString(),
                ExceptionTime = DateTimeOffset.Now
            }));
            //await _eventPublisher.PublishAsync(new ChannelEventSource("Create:ExLog",
            //    new SysLogEx
            //    {
            //        Account = userContext?.FindFirstValue(ClaimConst.CLAINM_ACCOUNT),
            //        Name = userContext?.FindFirstValue(ClaimConst.CLAINM_NAME),
            //        ClassName = context.Exception.TargetSite.DeclaringType?.FullName,
            //        MethodName = context.Exception.TargetSite.Name,
            //        ExceptionName = context.Exception.Message,
            //        ExceptionMsg = context.Exception.Message,
            //        ExceptionSource = context.Exception.Source,
            //        StackTrace = context.Exception.StackTrace,
            //        ParamsObj = context.Exception.TargetSite.GetParameters().ToString(),
            //        ExceptionTime = DateTimeOffset.Now
            //    }));

            // 写日志文件
            logger.LogError(context.Exception.ToString());

        }
    }
}
